﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LootPoints.Security;
using LootPoints.Warcraft;
using AjaxControlToolkit;

namespace LootPoints.Pages
{
    public partial class Adminpage : AdminPageSecurity
    {
        ModelContainer context;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!IsPostBack) Session["selectedCharacter"] = 1000000;
            context = new ModelContainer();
            reLoad();
        }

        protected void reLoad()
        {
            while (table.Rows.Count != 2) table.Rows.RemoveAt(table.Rows.Count - 1);

            List<Character> characters = (from c in context.Character orderby c.Name ascending select c).ToList();
            foreach (Character character in characters)
            {
                TableRow row = new TableRow() { CssClass = "Row" };
                row.Cells.Add(new TableCell() { Text = character.Group, HorizontalAlign = HorizontalAlign.Left });
                
                row.Cells.Add(new TableCell());

                TableCell cel = new TableCell() { HorizontalAlign = HorizontalAlign.Left };
                LinkButton lbtn = new LinkButton() { Text = character.Name, CausesValidation = false, ToolTip = character.Name, CssClass = "btnControl" };
                lbtn.Click += lbtn_Click;
                cel.Controls.Add(lbtn);
                row.Cells.Add(cel);

                TableCell cell = new TableCell() { HorizontalAlign = HorizontalAlign.Center };
                TextBox tb = new TextBox() { Text = character.EP.ToString(), CssClass = "tbControl", ToolTip = character.Name, AutoPostBack = true };
                tb.TextChanged += tbEP_TextChanged;
                cell.Controls.Add(tb);
                row.Cells.Add(cell);

                TableCell celll = new TableCell() { HorizontalAlign = HorizontalAlign.Center };
                TextBox tbb = new TextBox() { Text = character.GP.ToString(), CssClass = "tbControl", ToolTip = character.Name, AutoPostBack = true };
                tbb.TextChanged += tbGP_TextChanged;
                celll.Controls.Add(tbb);
                row.Cells.Add(celll);

                string rp; try { rp = (character.EP / character.GP).ToString(); } catch { rp = "0"; }
                TableCell cellll = new TableCell() { Text = rp, HorizontalAlign = HorizontalAlign.Center };
                row.Cells.Add(cellll);

                table.Rows.Add(row);
            }

            LoadRaidReference(context);
        }

        protected void LoadRaidReference(ModelContainer context)
        {
            while (tableReference.Rows.Count != 1) tableReference.Rows.RemoveAt(table.Rows.Count - 1);

            RSReference reference = (from c in context.RSReference select c).FirstOrDefault();
            if (reference == null)
            {
                reference = new RSReference();
                reference.Name = "default";
                context.RSReference.Add(reference);
                context.SaveChanges();
            }

            foreach (KeyValuePair<int, string[]> item in reference.List)
            {
                TableRow row = new TableRow();
                
                row.Cells.Add(new TableCell() { Text = item.Key.ToString(), HorizontalAlign = HorizontalAlign.Center, CssClass = "Row" });
                row.Cells.Add(new TableCell());
                
                TableCell criteriacell = new TableCell();
                TextBox criteriatb = new TextBox() { Text = item.Value[0], CssClass = "tbCriteria", ToolTip = item.Key.ToString() };
                criteriatb.TextChanged += criteriatb_TextChanged;
                criteriacell.Controls.Add(criteriatb);
                row.Cells.Add(criteriacell);

                row.Cells.Add(new TableCell());

                TableCell weightcell = new TableCell();
                TextBox weighttb = new TextBox() { Text = item.Value[1], CssClass = "tbWeight", ToolTip = item.Key.ToString() };
                weighttb.TextChanged += weighttb_TextChanged;
                weightcell.Controls.Add(weighttb);
                row.Cells.Add(weightcell);
                tableReference.Rows.Add(row);
            }
        }

        protected void weighttb_TextChanged(object sender, EventArgs e)
        {
            ModelContainer context = new ModelContainer();
            RSReference reference = (from c in context.RSReference select c).FirstOrDefault();
            try
            {
                Convert.ToInt32((sender as TextBox).Text);
                reference.List[Convert.ToInt32((sender as TextBox).ToolTip)][1] = (sender as TextBox).Text;
                switch (Convert.ToInt32((sender as TextBox).ToolTip))
                {
                    case 0:
                        reference.A01P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 1:
                        reference.A02P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 2:
                        reference.A03P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 3:
                        reference.A04P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 4:
                        reference.A05P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 5:
                        reference.A06P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 6:
                        reference.A07P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 7:
                        reference.A08P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 8:
                        reference.A09P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 9:
                        reference.A10P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 10:
                        reference.A11P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 11:
                        reference.A12P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 12:
                        reference.A13P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 13:
                        reference.A14P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    case 14:
                        reference.A15P = Convert.ToInt32((sender as TextBox).Text);
                        break;
                    default:
                        break;
                }
                context.SaveChanges();
            }
            catch { (sender as TextBox).Text = reference.List[Convert.ToInt32((sender as TextBox).ToolTip)][1]; }
            reLoad();
        }
        protected void criteriatb_TextChanged(object sender, EventArgs e)
        {
            ModelContainer context = new ModelContainer();
            RSReference reference = (from c in context.RSReference select c).FirstOrDefault();
            switch (Convert.ToInt32((sender as TextBox).ToolTip))
            {
                case 0:
                    reference.A01D = (sender as TextBox).Text;
                    break;
                case 1:
                    reference.A02D = (sender as TextBox).Text;
                    break;
                case 2:
                    reference.A03D = (sender as TextBox).Text;
                    break;
                case 3:
                    reference.A04D = (sender as TextBox).Text;
                    break;
                case 4:
                    reference.A05D = (sender as TextBox).Text;
                    break;
                case 5:
                    reference.A06D = (sender as TextBox).Text;
                    break;
                case 6:
                    reference.A07D = (sender as TextBox).Text;
                    break;
                case 7:
                    reference.A08D = (sender as TextBox).Text;
                    break;
                case 8:
                    reference.A09D = (sender as TextBox).Text;
                    break;
                case 9:
                    reference.A10D = (sender as TextBox).Text;
                    break;
                case 10:
                    reference.A11D = (sender as TextBox).Text;
                    break;
                case 11:
                    reference.A12D = (sender as TextBox).Text;
                    break;
                case 12:
                    reference.A13D = (sender as TextBox).Text;
                    break;
                case 13:
                    reference.A14D = (sender as TextBox).Text;
                    break;
                case 14:
                    reference.A15D = (sender as TextBox).Text;
                    break;
                default:
                    break;
            }
            context.SaveChanges();
            reLoad();
        }

        protected void lbtn_Click(object sender, EventArgs e)
        {
            string characterName = (sender as LinkButton).ToolTip;
            Character character = (from c in context.Character where c.Name == characterName select c).FirstOrDefault();
            Session["selectedCharacter"] = character.Id;
            lblTitle.Text = "edit character";
            tbCharacter.Text = character.Name;
            tbE.Text = character.Email;
            tbGroup.Text = character.Group;
            tbEP.Text = character.EP.ToString();
            tbGP.Text = character.GP.ToString();
            ddClass.SelectedValue = character.Class;
            ddLevel.SelectedValue = character.Level.ToString();
            ddRace.SelectedValue = character.Race;
            cbAdmin.Checked = character.Admin;
            
            reqP.Enabled = false;
            reqRP.Enabled = false;

            mpeAdd.Show();
        }

        protected void tbEP_TextChanged(object sender, EventArgs e)
        {
            string characterName = (sender as TextBox).ToolTip;
            Character character = (from c in context.Character where c.Name == characterName select c).FirstOrDefault();
            try
            {
                character.EP = Convert.ToInt32((sender as TextBox).Text);
                context.SaveChanges();
            }
            catch { (sender as TextBox).Text = character.EP.ToString(); }
            reLoad();
        }

        protected void tbGP_TextChanged(object sender, EventArgs e)
        {
            string characterName = (sender as TextBox).ToolTip;
            Character character = (from c in context.Character where c.Name == characterName select c).FirstOrDefault();
            try
            {
                character.GP = Convert.ToInt32((sender as TextBox).Text);
                context.SaveChanges();
            }
            catch { (sender as TextBox).Text = character.GP.ToString(); }
            reLoad();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) mpeAdd.Show();
            else
            {
                if ((int)Session["selectedCharacter"] == 1000000)
                {
                    Character character = (from c in context.Character where c.Name == tbCharacter.Text select c).FirstOrDefault();
                    if (character != null) lblCharacter.Text = "* already Exists";
                    else
                    {
                        try
                        {
                            character = new Character() { Name = tbCharacter.Text, EP = Convert.ToInt32(tbEP.Text), GP = Convert.ToInt32(tbGP.Text), Group = tbGroup.Text, Email = tbE.Text, Class = ddClass.SelectedItem.Text, Admin = cbAdmin.Checked, Level = Convert.ToInt32(ddLevel.SelectedItem.Text), Password = Hashing.CreateHash(tbRP.Text), Race = ddRace.SelectedItem.Text, Reset = false };
                            context.Character.Add(character);
                            context.SaveChanges();
                            btnCancel_Click(btnCancel, null);
                            reLoad();
                        }
                        catch { mpeAdd.Show(); }
                    }
                }
                else
                {
                    try
                    {
                        int selectedCharacterId = (int)Session["selectedCharacter"];
                        Character character = (from c in context.Character where c.Id == selectedCharacterId select c).FirstOrDefault();
                        character.Name = tbCharacter.Text;
                        character.EP = Convert.ToInt32(tbEP.Text);
                        character.GP = Convert.ToInt32(tbGP.Text);
                        character.Group = tbGroup.Text;
                        character.Email = tbE.Text;
                        character.Class = ddClass.SelectedItem.Text;
                        character.Admin = cbAdmin.Checked;
                        character.Level = Convert.ToInt32(ddLevel.SelectedItem.Text);
                        if (tbP.Text.Count() > 0) character.Password = Hashing.CreateHash(tbRP.Text);
                        character.Race = ddRace.SelectedItem.Text;
                        context.SaveChanges();
                        btnCancel_Click(btnCancel, null);
                        reLoad();
                    }
                    catch { mpeAdd.Show(); }
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            lblCharacter.Text = "";
            tbCharacter.Text = "";
            tbE.Text = "";
            tbGroup.Text = "";
            tbP.Text = "";
            tbEP.Text = "";
            tbGP.Text = "";
            tbRP.Text = "";
            cbAdmin.Checked = false;
            Session["selectedCharacter"] = 1000000;
            lblTitle.Text = "add character";

            reqP.Enabled = true;
            reqRP.Enabled = true;

            mpeAdd.Hide();
        }

        protected void lbtnLogoff_Click(object sender, EventArgs e)
        {
            Session.Clear();
            Response.Redirect("~/Default.aspx");
        }

        protected void lbtnLoad_Click(object sender, EventArgs e)
        {
            if (tbCharacter.Text != "")
            {
                try
                {
                    string[] character = new BattleNet().GetCharacter(tbCharacter.Text);
                    ddRace.SelectedValue = character[1];
                    ddClass.SelectedValue = character[2];
                    ddLevel.SelectedValue = character[3];
                }
                catch (Exception ex) { lblCharacter.Text = "Couldnt load..."; }
            }
            mpeAdd.Show();
        }



        protected void tbFilterGR_TextChanged(object sender, EventArgs e)
        {
            for (int i = 2; i < table.Rows.Count; i++)
                table.Rows[i].Visible = true;

            if (tbFilterGR.Text == "") tbFilterGR.Text = "filter...";
            else
            {
                for (int i = 2; i < table.Rows.Count; i++)
                    if (!table.Rows[i].Cells[0].Text.ToLower().Contains(tbFilterGR.Text.ToLower())) table.Rows[i].Visible = false;
            }
        }

        protected void tbFilterCH_TextChanged(object sender, EventArgs e)
        {
            for (int i = 2; i < table.Rows.Count; i++)
                table.Rows[i].Visible = true;

            if (tbFilterCH.Text == "") tbFilterCH.Text = "filter...";
            else
            {
                for (int i = 2; i < table.Rows.Count; i++)
                    if (!table.Rows[i].Cells[2].Text.ToLower().Contains(tbFilterCH.Text.ToLower())) table.Rows[i].Visible = false;
            }
        }

        protected void tbFilterEP_TextChanged(object sender, EventArgs e)
        {
            for (int i = 2; i < table.Rows.Count; i++)
                table.Rows[i].Visible = true;

            if (tbFilterEP.Text == "") tbFilterEP.Text = "filter...";
            else
            {
                for (int i = 2; i < table.Rows.Count; i++)
                    if (!(table.Rows[i].Cells[3].Controls[0] as TextBox).Text.Contains(tbFilterEP.Text)) table.Rows[i].Visible = false;
            }
        }

        protected void tbFilterGP_TextChanged(object sender, EventArgs e)
        {
            for (int i = 2; i < table.Rows.Count; i++)
                table.Rows[i].Visible = true;

            if (tbFilterGP.Text == "") tbFilterGP.Text = "filter...";
            else
            {
                for (int i = 2; i < table.Rows.Count; i++)
                    if (!(table.Rows[i].Cells[4].Controls[0] as TextBox).Text.Contains(tbFilterGP.Text)) table.Rows[i].Visible = false;
            }
        }

        protected void tbFilterPR_TextChanged(object sender, EventArgs e)
        {
            for (int i = 2; i < table.Rows.Count; i++)
                table.Rows[i].Visible = true;

            if (tbFilterPR.Text == "") tbFilterPR.Text = "filter...";
            else
            {
                for (int i = 2; i < table.Rows.Count; i++)
                    if (!table.Rows[i].Cells[5].Text.Contains(tbFilterPR.Text)) table.Rows[i].Visible = false;
            }
        }

        protected void btnCleanLoot_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < context.LootLog.ToList().Count; i++)
            {
                LootLog firstloot = context.LootLog.ToList()[i];
                List<LootLog> doubles = (from c in context.LootLog
                                         where
                                             c.Id != firstloot.Id &&
                                             c.Character.Name == firstloot.Character.Name &&
                                             c.ArmoryId == firstloot.ArmoryId &&
                                             c.Datetime == firstloot.Datetime
                                         select c).ToList();
                if (doubles.Count > 0)
                {
                    foreach (LootLog loot in doubles)
                    {
                        context.LootLog.Remove(loot);
                        context.SaveChanges();
                    }
                }
            }
            lblCleanLoot.Text = "Done!";
        }
    }
}